package com.dcsec.server.controller;

import cn.hutool.json.JSONUtil;
import com.dcsec.server.bean.PrintParam;
import com.dcsec.server.bean.Result;
import com.dcsec.server.zebra.ZebraPrinter;
import com.zebra.sdk.printer.discovery.DiscoveredUsbPrinter;
import com.zebra.sdk.printer.discovery.UsbDiscoverer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


public class ZebraPrinterController extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(ZebraPrinterController.class);

    @Override
    public void init(ServletConfig arg0) throws ServletException {
        System.out.println("servlet初始化");

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	doPost(request, response);
	}

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");

        try {

//            for (DiscoveredUsbPrinter printer : UsbDiscoverer.getZebraUsbPrinters()) {
//                log.error(printer.toString());
//            }

            String dataJSON = request.getParameter("dataJSON");
            List<PrintParam> printParams = JSONUtil.toList(dataJSON, PrintParam.class);

            ZebraPrinter.printToParams(printParams);
            doResponse(response, Result.createSuccessResult());
        } catch (Exception e) {
            log.error(e.getMessage());
            doResponse(response,Result.createErrorResult(e.getMessage()));
        }
    }

    /**
     * ajax输出数据
     * @param response
     * @param result
     * @throws IOException
     */
    protected void doResponse(HttpServletResponse response,Result result) throws IOException {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(JSONUtil.toJsonStr(result));
        response.getWriter().flush();
    }
}
